﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ObjectModel;
using System.Globalization;
using System.Reflection;

namespace SAIPS.Controllers.Controllers
{
	public class CustomerController : Controller
	{

		//
		// GET: /Customer/

		public ActionResult Index()
		{
			return View("Index",new Customer().select("", "Id", "CorporateName", "Name", "Description", "Document").ToList());
		}

		public ActionResult Edit(int? id)
		{
			return View(new Customer().select("where id=" + id).FirstOrDefault());
		}

		public ActionResult Delete()
		{
			return View("Index");
		}

		public ActionResult Create()
		{
			return View(new Customer());
		}

		public ActionResult Insert(FormCollection form)
		{
			var obj = fillObj(form);
			//TODO: address
			obj.insert();
			return Index();
		}
		
		public ActionResult Update(FormCollection form)
		{
			var obj = fillObj(form);
			obj.Id = Convert.ToInt32(form["Id"]);
			//TODO: address
			obj.update();
			return Index();
		}

		private static Customer fillObj(FormCollection form)
		{
			var obj = new Customer();
			obj.Name = form["name"];
			obj.CorporateName = form["corporatename"];
			obj.Birthdate = DateTime.Parse(form["birthdate"]);
			obj.Description = form["description"];
			obj.Document = form["document"];
			obj.MunicipalInscription = form["municipalinscription"];
			obj.StateInscription = form["stateinscription"];
			return obj;
		}
		public ActionResult Save(FormCollection form)
		{
			if (!String.IsNullOrEmpty(form["Id"]))
				return Update(form);
			return Insert(form);
		}
	}
}
